/*
 * @Descripttion: 
 * @version: 
 * @Author: yuxintao
 * @Date: 2022-04-20 14:49:54
 * @LastEditors: yuxintao
 * @LastEditTime: 2022-04-20 18:14:54
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <sys/select.h>

int sockfd;
char* IP = "192.168.223.128";
int PORT = 8888;
char sendbuf[1024], recvbuf[1024], filename[100];

void* readthread(void* arg) {
    pthread_detach(pthread_self());
    struct sockaddr_in server;
    int len;
    while (1) {  
        memset(recvbuf, 0, sizeof(recvbuf));
        recv(sockfd, recvbuf, sizeof(recvbuf), 0);
        if (strncmp(recvbuf, "close", 5) == 0) {
            close(sockfd);
            exit(0);
        }
        printf("%s", recvbuf);
        fflush(stdout);
    }
    return NULL;
}
void sigint(int sign) {
    memset(sendbuf, 0, sizeof(sendbuf));
    sprintf(sendbuf, "quit");
    send(sockfd, sendbuf, sizeof(sendbuf), 0);
    close(sockfd);
    exit(0);
}
int main() {
    signal(SIGINT, sigint);
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(IP);
    server.sin_port = htons(PORT);
    memset(sendbuf, 0, sizeof(sendbuf));
    strcpy(sendbuf, "seq");
    sendto(sockfd, sendbuf, sizeof(sendbuf), 0, (struct sockaddr*)&server, sizeof(server));
    int len;
    memset(recvbuf, 0, sizeof(recvbuf));
    fd_set r_set;
    FD_ZERO(&r_set);
    FD_SET(sockfd, &r_set);
    struct timeval t;
    t.tv_sec = 1;
    t.tv_usec = 0;
    if (select(sockfd + 1, &r_set, NULL, NULL, &t) <= 0) {
        sendto(sockfd, sendbuf, sizeof(sendbuf), 0, (struct sockaddr*)&server, sizeof(server));
    }
    recvfrom(sockfd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr*)&server, (socklen_t*)&len);
    printf("%s", recvbuf);
    fflush(stdout);
    if (strncmp(recvbuf, "fail", 4) == 0) {
        close(sockfd);
        exit(0);
    }
    connect(sockfd, (struct sockaddr*)&server, sizeof(server));
    pthread_t tid;
    pthread_create(&tid, NULL, readthread, NULL);
    while (1) {
        printf("please input the filename:");
        memset(filename, 0, 100);
        gets(filename);
        FILE* fp = fopen(filename, "r");
        if (!fp) {
            perror("fopen");
            exit(1);
        }
        while (1) {
            memset(sendbuf, 0, sizeof(sendbuf));
            fgets(sendbuf, sizeof(sendbuf), fp);
            if (feof(fp)) {
                break;
            }
            send(sockfd, sendbuf, strlen(sendbuf), 0);
        }
        fclose(fp);
        memset(sendbuf, 0, sizeof(sendbuf));
        sprintf(sendbuf, "over");
        send(sockfd, sendbuf, sizeof(sendbuf), 0);
    }
    return 0;
}